import json
import torch
import logging
from datetime import datetime
from pathlib import Path
from typing import Dict, Any, Optional

logger = logging.getLogger(__name__)

class ConfigManager:
    """
    配置管理类，负责保存和加载配置
    """
    
    def __init__(self, output_dir: Optional[Path] = None):
        """
        初始化配置管理器
        
        参数:
            output_dir: 配置文件输出目录
        """
        self.output_dir = output_dir
        if self.output_dir:
            self.output_dir.mkdir(parents=True, exist_ok=True)
    
    def save_config(
        self, 
        model_config: Dict[str, Any], 
        data_config: Dict[str, Any], 
        cmdb_id_mapping: Dict[str, int],
        anomaly_id: str = None
    ) -> str:
        """
        保存配置到JSON文件
        
        参数:
            model_config: 模型配置
            data_config: 数据配置
            cmdb_id_mapping: CMDB ID到索引的映射
            anomaly_id: 异常ID，用于文件命名
            
        返回:
            str: 保存的配置文件路径，如果保存失败则返回None
        """
        if not self.output_dir:
            logger.warning("未设置输出目录，无法保存配置")
            return None
            
        # 准备配置数据
        config = {
            "model_config": {k: v for k, v in model_config.items() if not isinstance(v, (torch.Tensor))},
            "data_config": data_config,
            "cmdb_id_mapping": cmdb_id_mapping,
            "saved_at": datetime.now().isoformat(),
            "anomaly_id": anomaly_id,
        }
        
        # 生成配置文件名
        filename = f"art_config.json"
        config_path = self.output_dir / filename
        
        # 保存配置
        try:
            with open(config_path, "w") as f:
                json.dump(config, f, indent=2)
            logger.info(f"配置已保存到 {config_path}")
            return str(config_path)
        except Exception as e:
            logger.error(f"保存配置时发生错误: {e}")
            return None
    
    def load_config(self, config_path: str) -> Dict[str, Any]:
        """
        从文件加载配置
        
        参数:
            config_path: 配置文件路径
            
        返回:
            Dict[str, Any]: 配置字典，如果加载失败则返回空字典
        """
        try:
            with open(config_path, "r") as f:
                config = json.load(f)
            logger.info(f"已从 {config_path} 加载配置")
            return config
        except Exception as e:
            logger.error(f"加载配置时发生错误: {e}")
            return {} 